<!-- 聊天详细页面 -->
<template>
    <div id='detail_container' @scroll="scrollHandle">
        <!-- 标题盒子 -->
        <div id="title_box">
            <div id="return_icon" @click="returnHadle"><img src="@/public/return.png" alt="" srcset=""></div>
            <div>{{ chatName }}</div>
            <!-- 邀请按钮 -->
            <div id="inviteBtn" v-if="groupOwner">
                <img src="@/public/group/add.png" alt="邀请" srcset="" @click="inviteHandle">
            </div>
        </div>
        <!-- 邀请表单模态框 -->
        <el-dialog v-model="dialogFormVisible" title="邀请用户" width="250">
            <el-form-item label="用户名：">
                <el-input v-model="inviteName" autocomplete="off" placeholder="请输入用户名" />
            </el-form-item>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="execCommit">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 聊天记录展示盒子 -->
        <div id="chats_box" ref="chatsBox" @scroll="scrollHandle">
            <!-- 遍历展示聊天消息 -->
            <div class="message_item" v-for="(item, index) of showRecords" :key="index"
                :class="{ 'right_message': item.sender == loginUserInfo.userId }">
                <div class="row_box">
                    <div class="sender_name" :class="{ 'self': item.sender == loginUserInfo.userId }">{{ item.name }}
                    </div>
                    <div class="sender_message">{{ item.message }}</div>
                </div>
            </div>
            <div style="height: 250px;" v-if="showEmojiPicker"></div>
        </div>
        <!-- 消息输入框 -->
        <div id="messageIptBox">
            <div id="row_ipt">
                <el-input id="msgIpt" style="height: 45px; width: 88%;" v-model="senderText" placeholder="请输入内容后发送"
                    @keyup.enter="senderHandler" />
                <div id="emoji_ico"><img src="@/public/emoji.png" alt="" srcset="" @click="showEmojiBox"></div>
            </div>
            <emoji-picker v-if="showEmojiPicker" @emoji-click="addEmoji"
                style="width: 100%; height: 250px;"
                search-placeholder="搜索表情..."></emoji-picker>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, nextTick } from "vue";
import { ElMessage } from 'element-plus';
import { getValueBykey, deleteToken, saveValue, getLoginUserId, getLoginUserName } from "@/indexDB/dbKV";
import { getAllChatRecord, addHistoryData, getGroupChatRecord } from "@/indexDB/dbHistory.js";
import axios from "@/public/axiosConfig.js";
import 'emoji-picker-element'; // emoji表情库
import { useRouter } from "vue-router";
import { webSocketManager } from "@/utils/websocket";

const router = useRouter();

// 当前聊天对象ID
const receiverId = ref("");
// TODO 聊天记录展示列表
const showRecords = ref([]);
// 聊天对象名称
let chatName = ref("chat_default")
// 输入的文本
let senderText = ref("");
// websocket连接对象
const socket = ref();
// 聊天盒子
const chatsBox = ref(null);
// 当前登录用户信息
const loginUserInfo = ref();
// 是否为群主
let groupOwner = ref(false);
// 邀请模态框显示控制
let dialogFormVisible = ref(false);
// 邀请表单-邮箱地址输入
let inviteName = ref("");
// 表情集的显示
const showEmojiPicker = ref(false);

// 消息格式封装
let messageObj = reactive({
    fromUserId: "", // 从哪来（用户id）
    toId: "", // 到哪去（用户id 或 群组id）
    messageType: "", // 消息类型（public, group, person）
    content: "", // 消息内容
    groupName: "" //群组名称，私聊可为空
})

// 消息处理器 - 修正版
const messageHandler = async (historyO) => {
  

  console.log('Detail页面收到消息:', historyO);

  console.log('=== 收到消息详情 ===');
  console.log('消息ID:', historyO.messageId);
  console.log('发送者:', historyO.sender);
  console.log('接收者:', historyO.receiver);
  console.log('消息类型:', historyO.msgType);
  console.log('内容:', historyO.message);
  
  try {
    // 获取当前聊天窗口信息
    let currentChatInfoStr = await getValueBykey("chat_receiver");
    if (!currentChatInfoStr) {
      console.log('没有当前聊天窗口，忽略消息');
      return;
    }
    
    let currentChatInfo = JSON.parse(currentChatInfoStr);
    const currentReceiverId = currentChatInfo.receiverId;
    console.log('当前聊天窗口ID:', currentReceiverId);

    // 检查是否已经显示过（通过ID）
    const isDuplicate = showRecords.value.some(item => 
      item.messageId === historyO.messageId
    );
    
    if (isDuplicate) {
      console.log('消息已显示过，跳过重复显示');
      return;
    }

    // 保存到IndexDB
    await addHistoryData(historyO);
    
    // 给消息添加发送者名称
    let name = await getNameByUserId(historyO.sender);
    historyO['name'] = name;

    // 判断是否显示在当前窗口
    let shouldDisplay = false;
    
    if (historyO.msgType === "person") {
      shouldDisplay = historyO.sender === currentReceiverId || historyO.receiver === currentReceiverId;
      console.log('私聊消息，是否显示:', shouldDisplay);
    }
    else if (historyO.msgType === "group" || historyO.msgType === "public") {
      shouldDisplay = historyO.receiver === currentReceiverId;
      console.log('群聊消息，是否显示:', shouldDisplay);
    }

    if (shouldDisplay) {
      showRecords.value = [...showRecords.value, historyO];
      scrollToBottom();
      console.log('消息已添加到聊天窗口');
    } else {
      console.log('消息不属于当前聊天窗口，不显示');
    }
  } catch (error) {
    console.error('处理消息错误:', error);
  }
  
  /* try {
    // 保存到IndexDB
    await addHistoryData(historyO);
    
    // 给消息添加发送者名称
    let name = await getNameByUserId(historyO.sender);
    historyO['name'] = name;

    // 获取当前聊天窗口信息
    let currentChatInfoStr = await getValueBykey("chat_receiver");
    if (!currentChatInfoStr) return; // 没有当前聊天窗口
    
    let currentChatInfo = JSON.parse(currentChatInfoStr);
    const currentReceiverId = currentChatInfo.receiverId;

    // 判断是否显示在当前窗口
    let shouldDisplay = false;
    
    // 私聊消息：发送者或接收者是当前聊天对象
    if (historyO.msgType === "person") {
      shouldDisplay = historyO.sender === currentReceiverId || historyO.receiver === currentReceiverId;
    }
    // 群聊消息：接收者是当前群组
    else if (historyO.msgType === "group" || historyO.msgType === "public") {
      shouldDisplay = historyO.receiver === currentReceiverId;
    }

    if (shouldDisplay) {

      // 检查是否已经显示过（通过ID）
      const isDuplicate = showRecords.value.some(item => 
        item.messageId === historyO.messageId
      );
      
      if (isDuplicate) {
        console.log('消息已本地渲染，跳过重复显示');
        return;
      }

      showRecords.value = [...showRecords.value, historyO];
      scrollToBottom();
      console.log('消息已显示在聊天窗口');
    } else {
      console.log('消息不属于当前聊天窗口，不显示');
    }
  } catch (error) {
    console.error('处理消息错误:', error);
  } */
};

  // 判断消息是否应该在当前聊天窗口显示
function shouldDisplayMessage(message, currentReceiverId) {
  // 如果是私聊消息
  if (message.msgType === "person") {
    // 当前窗口是私聊窗口，且对方是聊天对象
    return message.sender === currentReceiverId || message.receiver === currentReceiverId;
  }
  
  // 如果是群聊或公共消息
  if (message.msgType === "group" || message.msgType === "public") {
    // 当前窗口是这个群组的聊天窗口
    return message.receiver === currentReceiverId;
  }
  
  return false;
}


//页面加载，获取当前标中的聊天对象ID，从IndexDB中取出所有聊天记录
onMounted(async() => {
    initChatRecords();

    // 保存当前聊天窗口ID到全局，供Home页面判断
    let chatInfoStr = await getValueBykey("chat_receiver");
    if (chatInfoStr) {
      let chatInfo = JSON.parse(chatInfoStr);
      window.currentChatReceiverId = chatInfo.receiverId;
    }

    // 添加消息处理器
    webSocketManager.addMessageHandler(messageHandler);

    // 连接websocket实时收发消息
    // connectionWebsocker();
    // 页面加载完成时，自动滚动到底部
    nextTick(() => {
        scrollToBottom();
    });
    // 获取当前用户信息
    getLoginUserInfo();
})

// 点击表情图标, 显示图标集
function showEmojiBox() {
    showEmojiPicker.value = !showEmojiPicker.value
    // 滑动到最底部, 兼容聊天视图显示
    setTimeout(() => {
        // console.log("滚动");
        if (chatsBox.value) {
            chatsBox.value.scrollTop = chatsBox.value.scrollHeight
        }
    }, 50)
}

// 选择表情图标, 追加到输入框内容之后
function addEmoji(e){
    senderText.value += e.detail.unicode;
}

async function getLoginUserInfo() {
    loginUserInfo.value = await getValueBykey("userInfo");

    // 检查当前登录用户是否是此聊天群主
    // 解析出当前聊天对象ID
    let receiverInfoStr = await getValueBykey("chat_receiver");
    let receiverInfo = JSON.parse(receiverInfoStr);

    const { data: res } = await axios.get(`/groupInfos/checkGroupOwner/${receiverInfo.receiverId}/${loginUserInfo.value.userId}`);
    if (res.code == 0) {
        groupOwner.value = false;
        return 1;
    }
    // 是群主，显示【邀请】群员按钮
    groupOwner.value = true;

}

// 页面加载，自动滑动到最底部
const scrollToBottom = () => {
    if (chatsBox.value) {
        setTimeout(() => {
            if (chatsBox.value) {
            chatsBox.value.scrollTop = chatsBox.value.scrollHeight
        }
        }, 700)
    }
};

// 邀请处理器
function inviteHandle() {
    dialogFormVisible.value = true;
}

// 邀请-执行提交
async function execCommit() {
    if (inviteName.value == loginUserInfo.value.name){
        showMessage("error", "不能邀请自己！");
        return 0;
    }
    // 构造请求参数对象
    let chatInfoStr = await getValueBykey("chat_receiver");
    let chatInfo = JSON.parse(chatInfoStr);

    const { data: res } = await axios.get(`/groupUsers/inviteUserIntoGroup/${chatInfo.receiverId}/${inviteName.value}`);
    if(res.code == 0){
        showMessage("error", "邀请失败，请稍后重试!")
        return 0;
    }

    showMessage("success", res.data);
    dialogFormVisible.value = false;
}   

// 发送消息处理器
async function senderHandler() {
    sendMessage();
}

// 页面加载，获取当前聊天对象的历史记录
async function initChatRecords() {
    // 从indebDB中取出聊天对象ID
    let chatInfoStr = await getValueBykey("chat_receiver");
    let chatInfo = JSON.parse(chatInfoStr);
    receiverId.value = chatInfo.receiverId;

    let records = [];

    let execType = await checkUserType(receiverId.value);

    // 判定聊天对象是私人用户还是群组
    if (!execType) {
        // 不是用户ID，代表不是私聊，直接根据群组id获取历史消息
        records = await getGroupChatRecord(receiverId.value);
    } else {
        // 获取私聊用户记录
        records = await getAllChatRecord(receiverId.value);
    }
    // console.log(`获取到用户：【${chatInfo.name}】的所有聊天记录数量：${records.length}`);

    // 遍历添加历史记录对象，根据发送者ID查询出发送者名称
    for (let item of records) {
        let name = await getNameByUserId(item.sender);
        item['name'] = name;
    }

    showRecords.value = records;

    // 动态获取聊天对象名称设置为标题
    chatName.value = chatInfo.name;
    if (records.length == 0) {
        return 1;
    }
}

// 检查ID是否为用户ID 
async function checkUserType(userId) {
    const { data: res } = await axios(`/userInfos/checkId?userId=${userId}`);
    return res;
}

// 根据ID查用户名
async function getNameByUserId(userId) {
    const { data: res } = await axios(`/userInfos/getNameByUserId?userId=${userId}`);
    return res.data;
}

// websocket连接-配置类
/* async function connectionWebsocker() {
    // console.log("init connection websocket===>");
    // 取出登录后的 token 信息，用于 WebSocket 的验证连接
    const token = await getValueBykey("token")// 假设 token 保存在 localStorage 中
    // socket.value = new WebSocket(`ws://localhost:8889/chat?token=${token}`);
    socket.value = new WebSocket(`ws://chatroom:8889/chat?token=${token}`);

    // 监控 WebSocket 状态
    socket.value.onopen = () => {
        // console.log('连接socket成功');
    };

    socket.value.onclose = (event) => {
        if (event.wasClean) {
            // console.log(`WebSocket 连接已关闭，状态码：${event.code}，原因：${event.reason}`);
            returnLoginPage(0);
        } else {
            // console.error('WebSocket 连接意外关闭');
            returnLoginPage(1)
        }
    };

    socket.value.onerror = (error) => {
        // console.error('WebSocket 连接错误', error);
        returnLoginPage(1)
    };

    // 接收消息
    socket.value.onmessage = async (event) => {
        // 将收到的消息（一条历史记录）转为对象
        let historyO = JSON.parse(event.data);
        // 将消息动态添加到页面显示
        // console.log(`收到${historyO.sender}用户的消息：${historyO.message}`);
        // 将接收到的数据存入IndexDB，作本地持久化
        addHistoryData(historyO);

        // 给聊天对象动态查询并添加名称字段
        let name = await getNameByUserId(historyO.sender)
        historyO['name'] = name;

        // 收到消息，如果接收者为群组类型，判断接收者ID决定是否渲染
        if (historyO.receiver == receiverId.value && historyO.msgType != "person") {
            // 显示到页面
            showRecords.value = [...showRecords.value, historyO];
            // console.log("群组聊天222");
            return 1;
        }

        // 如果是私人聊天，则需要判断消息发送者是否为聊天对象
        if (historyO.sender == receiverId.value && historyO.msgType == "person") {
            showRecords.value = [...showRecords.value, historyO];
            // console.log("私人聊天111");
        }

        // console.log(receiverId.value, "++++++++");
        // console.log("收到并反序列化的对象：", historyO);
    };
} */

// 构造消息对象
async function createMessage(toId, msgType, content, groupName) {
    let userInfo = await getValueBykey("userInfo");
    messageObj.fromUserId = userInfo.userId;
    messageObj.toId = toId;
    messageObj.messageType = msgType;
    messageObj.content = content;
    messageObj.groupName = groupName;
}

// 发送消息-测试
// 发送消息 - 修正版
async function sendMessage() {
  console.log('开始发送消息...');
  
  if (!senderText.value.trim()) {
    showMessage("warning", "消息不能为空");
    return;
  }

  try {
    // 获取聊天对象信息
    let chatInfoStr = await getValueBykey("chat_receiver");
    let chatInfo = JSON.parse(chatInfoStr);
    receiverId.value = chatInfo.receiverId;

    // 获取当前用户信息
    if (!loginUserInfo.value) {
      loginUserInfo.value = await getValueBykey("userInfo");
    }

    // 确定消息类型
    let checkResult = await checkUserType(chatInfo.receiverId);
    let messageType = checkResult ? "person" : "group";
    
    if (chatInfo.receiverId == "a4b14014-42c5-4a51-9ded-7de028d252e6") {
      messageType = "public";
    }

    // 生成唯一消息ID（时间戳+随机数）
    const messageId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);

    // 构造消息对象
    const messageObj = {
    fromUserId: loginUserInfo.value.userId,
    toId: chatInfo.receiverId,
    messageType: messageType,
    content: senderText.value,
    groupName: chatInfo.name,
    messageId: messageId // 添加唯一ID
  };

    // 立即本地渲染（带唯一ID）
    const localMessage = {
      sender: loginUserInfo.value.userId,
      receiver: chatInfo.receiverId,
      message: senderText.value,
      msgType: messageType,
      timestamp: Date.now(),
      name: loginUserInfo.value.name || '我',
      groupName: messageType === "person" ? "" : chatInfo.name,
      messageId: messageId // 同样的ID
    };
    
    console.log('构造的消息:', messageObj);

    // 发送消息
    const success = webSocketManager.sendMessage(messageObj);
    
    if (success) {
      console.log('消息发送成功');
      
      // 无论是私聊还是群聊，都立即本地渲染（优化用户体验）
      /* const localMessage = {
        sender: loginUserInfo.value.userId,
        receiver: chatInfo.receiverId,
        message: senderText.value,
        msgType: messageType,
        timestamp: Date.now(),
        name: loginUserInfo.value.name || '我',
        groupName: messageType === "person" ? "" : chatInfo.name
      }; */
      
      await addHistoryData(localMessage);
      showRecords.value = [...showRecords.value, localMessage];
      scrollToBottom();
      
      senderText.value = "";
    } else {
      showMessage("error", "发送失败，请检查网络连接");
    }
  } catch (error) {
    console.error('发送消息错误:', error);
    showMessage("error", "发送失败");
  }
}

async function savePriveSenderRecord(hisObj) {
    // 将私发消息进行存储，并且显示到聊天页面
    await addHistoryData(hisObj);

    // 给聊天对象动态查询并添加名称字段
    let name = await getNameByUserId(hisObj.sender)
    hisObj['name'] = name;

    // 动态显示到聊天页面
    showRecords.value = [...showRecords.value, hisObj];
}

// 返回上一页
function returnHadle() {
    router.back()
}

// 通用消息提示函数
function showMessage(messageType, messageText) {
  ElMessage({
    message: messageText,
    type: messageType,
  })
}

// 出现连接错误，跳转到登录页
function returnLoginPage(errorStatus) {
  if (errorStatus == 0) {
    ElMessage({
      message: '登录状态异常，请重新登录！',
      type: 'error',
    });
  } else {
    ElMessage({
      message: '登录超时，请重新登录',
      type: 'info',
    });
  }

  setTimeout(() => {
    router.push("/login/");
  }, 500)
}



onUnmounted(() => {
  // 清理全局变量
  window.currentChatReceiverId = null;
  webSocketManager.removeMessageHandler(messageHandler);
});

</script>

<style scoped>
#title_box {
    max-width: 700px;
    font-size: 17px;
    box-sizing: border-box;
    background-color: #d7e5ee;
    width: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    padding: 15px 20px;
    display: flex;
    justify-content: center;
    align-content: center;
    z-index: 999;
}

.sender_name {
    font-size: 13px;
    color: #7d7a7a;
    padding-bottom: 5px;
    padding-left: 5px;
}

#detail_container {
    height: 100vh;
    width: 100%;
    box-sizing: border-box;
    /* background-color: #eeeeee; */
}

#chats_box {
    box-sizing: border-box;
    padding: 0px;
    margin: 0px;
    margin-top: 60px;
    padding-bottom: 60px;
    height: 100vh;
    width: 100%;
    overflow-y: auto;
    /* border: solid #2733d5 1px; */
    position: relative;
}

.message_item {
    padding: 10px 10px;
    position: relative;
    font-size: 14px;
    border-radius: 10px;
    display: flex;
    justify-content: left;
}

.row_box {
    position: relative;
    width: max-content;
}


.self {
    color: #36ad3c;
}

.right_message {
    justify-content: right;
}

.sender_message {
    background-color: #fff;
    padding: 10px 10px;
    border-radius: 9px;
}

#messageIptBox {
    box-sizing: border-box;
    width: 100vw;
    position: fixed;
    bottom: 0px;
    left: 0px;
    background-color: #fcfcfc;
}

#return_icon {
    position: absolute;
    left: 7px;
    top: 15px;
}

#return_icon img {
    width: 22px;
}

/* #messageIptBox input{
    height: 100px;
} */
#inviteBtn {
    position: absolute;
    right: 13px;
    top: 13px;
}

#inviteBtn img {
    width: 22px;
}

#row_ipt {
    display: flex;
}

#emoji_ico {
    position: relative;
    left: 8px;
    top: 8px;
}

#emoji_ico img {
    width: 28px;
}
</style>